package com.iflytek.autoCompareTool.utils;


import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Create :　2014-08-01
 * last modify by llchen12 on 2018/6/5
 *
 * @author clliu2
 */
public class XLSXWrite {

    private static Logger logger = LoggerFactory.getLogger(XLSXWrite.class);

    private SXSSFWorkbook writeWorkBook;

    private Sheet writeSheet;

    private CellStyle redColorCell;
    private CellStyle fontCell;

    private static byte[] ENPTY_BYTES = new byte[]{};

    /**
     * 初始化sheet
     */
    public XLSXWrite() {
        writeWorkBook = new SXSSFWorkbook(1000);
        writeSheet = writeWorkBook.createSheet();
        //设置红色
        CellStyle styleRed = createCell();
        styleRed.setFillForegroundColor(IndexedColors.RED.getIndex());
        styleRed.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font font = writeWorkBook.createFont();
        font.setFontName("Arial");
        font.setFontHeightInPoints((short) 10);
        styleRed.setFont(font);
        this.redColorCell = styleRed;
        //设置默认字体
        CellStyle fontCell = createCell();
        fontCell.setFont(font);
        this.fontCell = fontCell;
    }

    /**
     * 创建diff的sheet
     */
    public void newSheetXLSXWrite(int number, String sheetName) {
        writeSheet = writeWorkBook.createSheet();
        writeWorkBook.setSheetName(number + 1, sheetName);
    }

    /**
     * 单元格
     */
    private CellStyle createCell() {
        CellStyle style = writeWorkBook.createCellStyle();
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    /**
     * 设置单元格的值
     */
    public void setCellValue(int rowNum, int colNum, String value, boolean isRed) {
        if (null == value) {
            return;
        }
        Row row = writeSheet.getRow(rowNum);
        if (null == row) {
            row = writeSheet.createRow(rowNum);
        }
        Cell cell = row.getCell(colNum);
        if (null == cell) {
            cell = row.createCell(colNum);
        }
        cell.setCellValue(value);
        if (isRed) {
            cell.setCellStyle(redColorCell);
        } else {
            cell.setCellStyle(fontCell);
        }
    }

    public ByteArrayOutputStream getOutputStream() throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        writeWorkBook.write(bos);
        writeWorkBook.close();
        return bos;
    }


    public byte[] getBytes() {
        byte[] bytes = ENPTY_BYTES;
        try {
            ByteArrayOutputStream bos = getOutputStream();
            bytes = bos.toByteArray();
        } catch (IOException e) {
           logger.error("获取Excel输出字节失败",e);
        }
        return bytes;
    }

    /**
     * 将excel写入文件
     */
    public boolean writeToFile(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return false;
        }
        FileOutputStream out = null;
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                File fileParent = new File(file.getParent());
                fileParent.mkdirs();
                //fileParent.createNewFile();
            }
            out = new FileOutputStream(fileName);
        } catch (Exception e) {
            logger.error("写excel异常", e);
        }
        try {
            // 判断文件是否被打开，如果打开，则重命名
            if (null == out) {
                out = new FileOutputStream(fileName + ".output."
                        + String.valueOf(System.currentTimeMillis()));
            }
            writeWorkBook.write(out);
        } catch (Exception e) {
            logger.error("保存文件失败." + fileName);
            return false;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    //ignore
                }
            }
            close();
        }
        logger.debug("保存文件成功." + fileName);
        return true;
    }


    /**
     * 保存diff后移出第一个空的sheet
     */
    public void removeSheetOne() {
        writeWorkBook.removeSheetAt(0);
    }

    /**
     * 关闭工作空间
     **/
    public void close() {
        writeWorkBook.dispose();
    }
}
